<?php

namespace app\util;

/*
 * 百度~人脸替换（视频换脸）
 */

class Baidufacecg {
    /*
     * 人脸融合
     */

    public function facecg($srca, $srcb) {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = 'client_credentials';
        $post_data['client_id'] = '2mqpn0gLoQdMPzwTlsQo9Gdr';
        $post_data['client_secret'] = 'fk2vGoSPdyP0sqBZDmRVZ4cnxu9Burt8';
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = $this->request_post($url, $post_data); //获取token
        $res = json_decode($res, true);
        $access_token = $res['access_token'];

        $token = $access_token;
        $url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=' . $token;
        $arr = ['image_template' => [
                'image' => $srca,
                'image_type' => 'BASE64',
                'quality_control' => 'NONE' //质量控制 NONE: 不进行控制 LOW:较低的质量要求 NORMAL: 一般的质量要求 HIGH: 较高的质量要求 默认NONE
            ],
            'image_target' => [
                'image' => $srcb,
                'image_type' => 'BASE64',
                'quality_control' => 'NONE'
            ],
            'merge_degree' => 'COMPLETE',
            'version' => '2.0',
        ];
        $bodys = json_encode($arr);
        //print_r($bodys);die;
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res, TRUE);

        if ($res['error_code'] == 0) {
            $folder = 'baidufacecg';
            //上传头像
            $base64_img = trim($res['result']['merge_image']);
            $base64_img = 'data:image/jpg;base64,' . $base64_img;
            $file = new File();
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
                $type = $result[2];
                if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                    $mode = config('appconfig.app_production');
                    if ($mode) {
                        $publicFolder = 'kkmimg';
                    } else {
                        $publicFolder = 'testkkmimg';
                    }
                    $path = ROOT_PATH . '../' . $publicFolder;
                    $path2 = '/kkmai/' . $folder . '/' . date('Ymd') . '/' . time() . substr(microtime(), 2, 4) . mt_rand(1000, 9999) . '.' . $type;
                    $savename = $path . $path2;
                    $dirPath = $path . '/kkmai/' . $folder . '/' . date('Ymd') . '/';
                    if (!is_dir($dirPath)) {
                        $flag = mkdir($dirPath, 0777, true);
                    }
                    if (file_put_contents($savename, base64_decode(str_replace($result[1], '', $base64_img)))) {
                        //echo "上传成功";
                    } else {
                        ///return Utils::ajaxReturn(3, '图片上传失败', null);
                    }
                } else {
                    //return Utils::ajaxReturn(3, '图片上传类型错误', null);
                }
            } else {
                //return Utils::ajaxReturn(3, '文件错误', null);
            }

            $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($path2, PATHINFO_DIRNAME), false, $savename);
            if (!$curlPhoto) {
                //return Utils::ajaxReturn(3, '图片上传失败', null);
            } else {
                //return Utils::ajaxReturn(0, '上传成功', config('appconfig.ImgPath') . $publicFolder . $path2);
            }
            $sendResult = [
                'code' => '0',
                'msg' => '成功',
                'data' =>  config('appconfig.ImgPath') . $publicFolder . $path2,
            ];
            return $sendResult;
        } else {
            $sendResult = [
                'code' => '1',
                'msg' => $res['error_msg'],//'换脸失败，请上传清晰的脸部照片'
                'data' => null,
            ];
            return $sendResult;
        }
    }

    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init(); //初始化curl
        curl_setopt($curl, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0); //设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1); //post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl); //运行curl
        curl_close($curl);

        return $data;
    }

}
